package org.csc.sss.api.config;

import io.shardingsphere.core.api.algorithm.sharding.ListShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.ShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class MyComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, Collection<ShardingValue> shardingValues) {

        for (String availableTargetName : availableTargetNames) {
            for (ShardingValue shardingValue : shardingValues) {
                Object[] values = this.getShardingValue(shardingValues, shardingValue.getColumnName());
                Object value = values[0];
                if (shardingValue.getColumnName().equals("type")) {
                    if (availableTargetName.endsWith(Integer.parseInt(value.toString()) % 2 + "")) {
                        return Arrays.asList(availableTargetName);
                    }
                }
            }
        }

        return null;
    }

    private Object[] getShardingValue(Collection<ShardingValue> shardingValues, final String key) {
        Iterator<ShardingValue> iterator = shardingValues.iterator();
        while (iterator.hasNext()) {
            ShardingValue next = iterator.next();
            if (next instanceof ListShardingValue) {
                ListShardingValue value = (ListShardingValue) next;
                if (value.getColumnName().equals(key)) {
                    return value.getValues().toArray();
                }
            }
        }
        return null;
    }

}
